﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

namespace ButtonBuilder.Plugin
{
    public class ActionResult
    {
        public static readonly ActionResult Empty = new ActionResult();

        public Action Source { get; set; }

        public Exception Error { get; set; }

        public string NextPage { get; set; }
    }

    public class ActionEventArgs : EventArgs
    {
        public ActionEventArgs(ActionResult result)
        {
            Result = result;
        }

        public ActionResult Result
        {
            get;
            set;
        }
    }

    public delegate void ActionHandler(object sender, ActionEventArgs e);


    public class ActionParam
    {
        [XmlAttribute("name")]
        public string Name
        {
            get;
            set;
        }

        [XmlAttribute("type")]
        public string Type
        {
            get;
            set;
        }

        public string Value
        {
            get;
            set;
        }
    }

    public class Action : IPlugin
    {
        protected Action()
        {
            Parameters = new List<ActionParam>();
        }

        public string Name
        {
            get;
            set;
        }

        [XmlArrayItem(ElementName = "Parameter")]
        public List<ActionParam> Parameters
        {
            get;
            set;
        }

        public string GetParam(string paramName)
        {
            ActionParam param = Parameters.SingleOrDefault(p => p.Name.Equals(paramName));

            if (param != null)
            {
                return param.Value;
            }

            return null;
        }

        public void PutStringParam(string paramName, string value)
        {
            PutParam(paramName, typeof(string), value);
        }

        public void PutFileParam(string paramName, string value)
        {
            PutParam(paramName, typeof(System.IO.File), value);
        }

        private void PutParam(string paramName, Type paramType, string value)
        {
            ActionParam param = Parameters.SingleOrDefault(p => p.Name.Equals(paramName));

            if (param == null)
            {
                param = new ActionParam()
                {
                    Name = paramName,
                    Type = paramType.FullName
                };

                Parameters.Add(param);
            }

            param.Value = value;
        }

        public virtual ActionResult DoIt()
        {
            return ActionResult.Empty;
        }

        public virtual void Init()
        {

        }
    }
}
